%%离散余弦变换加水印，解水印按照加的思路逆过来
clc;clear;close all;
%% read data
im = double(imread('football.jpg'))/255;
mark = double(imread('watermark.png'))/255;
figure, imshow(im),title('original image');
figure, imshow(mark),title('watermark');
alpha=1;
RGB = imread('football.jpg');
I = im2gray(RGB);
FA=dct2(I);
RGB(:,:,1)=FA;
RGB(:,:,2)=FA;
RGB(:,:,3)=FA;
FA2=double(RGB);
figure, imshow(FA),title('original image');
imsize = size(im);
TH=zeros(imsize(1)*0.5,imsize(2),imsize(3));
TH1 = TH;
TH1(1:size(mark,1),1:size(mark,2),:) = mark;
M1=randperm(0.5*imsize(1));
M=sort(M1);
N1=randperm(imsize(2));
N=sort(N1);
save('encode.mat','M','N');
for i=1:imsize(1)*0.5
    for j=1:imsize(2)
        TH(i,j,:)=TH1(M(i),N(j),:);
    end
end
mark_ = zeros(imsize(1),imsize(2),imsize(3));
mark_(1:imsize(1)*0.5,1:imsize(2),:)=TH;
for i=1:imsize(1)*0.5
    for j=1:imsize(2)
        mark_(imsize(1)+1-i,imsize(2)+1-j,:)=TH(i,j,:);
    end
end
figure,imshow(mark_),title('encoded watermark');

figure,imshow(FA2);title('Spectrum of original image');
FB=FA2+alpha*double(mark_);%给图像加上水印
figure,imshow(FB); title('Spectrum of watermarked image');

FAO1=idct2(FB(:,:,1));
FAO2
FAO3
figure,imshow(FAO); title('Watermarked image');

